var express = require('express');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var common = require('./routes/common'); // 接口验证模块
var project = require('./routes/project'); // 项目模块
var renderData = require('./routes/renderData'); // 渲染模块
var folder = require('./routes/folder'); // 文件夹模块
var api = require('./routes/api'); // api
var key = require('./routes/key'); // 关键字模块
var cache = require('./routes/cache'); // 缓存模块
var model = require('./routes/model'); // 数据模型
var fun = require('./routes/fun'); // 自定义方法模块
var url = require('./routes/url'); // url 模块
var user = require('./routes/user') // 用户模块

global.query = require('./database/DB'); // 数据库模块
global.asyncQuery = require('./database/asyncQuery'); // 同步数据库操作模块
global.Permission = require('./database/checkProjectPermission'); // api 用户权限验证功能


var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());


app.use('/', function (req, res, next) {
  next();
});

app.use('/', common);
app.use('/', project);
app.use('/', renderData);
app.use('/', folder);
app.use('/', api);
app.use('/', key);
app.use('/', cache);
app.use('/', model);
app.use('/', fun);
app.use('/', url);
app.use('/', user);



// catch 404 and forward to error handler
app.use(function (req, res, next) {
  res.status(404);
  res.json({
    code: '404',
    msg: 'not find'
  });
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  // res.locals.message = err.message;
  // res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json({
    code: err.status,
    msg: err.message
  });
});

module.exports = app;
